package adversarial;

import env.Action;
import agents.AbsAgent;
import env.Enviroment;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

public class MinMaxAgent extends AbsAgent {

    private static int MAX_DEPTH = 22;
    //private final static long MAX_TIME = 2000;
    private final static boolean debug = true;
    private final static int d = 2;

    public MinMaxAgent(String name, int row, int col) {
        super(name, row, col);
        super.setIcon(new ImageIcon("images/cow.jpg"));
    }

    @Override
    public Action getMove() {
        AbsAgent enemy = null;
        for (AbsAgent a : Enviroment.env.agents) {
            if (a != this) {
                enemy = a;
                break;
            }
        }
        State root = new State(Enviroment.env.flags, getState(), enemy.getState(), null, Enviroment.getRemainingMoves());
        Action ans = null;
        long start = System.currentTimeMillis();
        long end = start;
        count = 0;
        hits = 0;
        miss = 0;
        int best = -1000;
        System.out.println("# getMove for  " + this);
        System.out.println("# ---------------------------");
        //for (int i = MAX_DEPTH; i < 100 && (end - start) < MAX_TIME; i += 10) {
        //best = -1000;
        for (State child : root.expand()) {
            long temp = System.currentTimeMillis();
            System.out.println("# getMove: current best is "+best+", checking " + child);
            int x = -maxiMaxAlphaBeta(child, 1, MAX_DEPTH, -1000, -best); //FUCK ME THIS MISTAKE WAS HARD TO FIND
            if (x > best) {
                System.out.println("# getMove " + child.getLastAction() + " (" + x + ") is BETTER than " + ans + " (" + best + ")!");
                best = x;
                ans = child.getLastAction();
            } else {
                System.out.println("# getMove " + child.getLastAction() + " (" + x + ") is not better than " + ans + " (" + best + ").");
            }
            end = System.currentTimeMillis();
            System.out.println("-------------- took " + (end - temp) + " msec  (total time=" + (end - start) + ") -----------------");

        }

        //}
        System.out.println("##########\n########## getMove " + getName() + " chose [" + ans + "] as the best move (score " + best + ") in max depth " + MAX_DEPTH + ".");
//        System.out.println(MAX_DEPTH + "," + binary(State.useHash) + "," + binary(State.useSort) + "," + binary(State.useComplexCompare) + "," + count + "," + (end - start));
        System.out.println("search is finished after " + (end - start) + " msec   and " + count + " calls to maximax.  memo.size=" + memo.size() + ", hit=%" + (100.0 * hits / (hits + miss)));

        //System.exit(0);
        if (debug) {
            try {
                System.out.println("hit return to continue... ****");
                System.in.read();
            } catch (IOException ex) {
                Logger.getLogger(Enviroment.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("\n\n\n");
        return ans;
    }

    /**
     * AI
     * returns the best possible score that the first player to move in s can hope for.
     * @param s
     * @param depth
     * @param max_depth
     * @param alpha
     * @param beta
     * @return
     */
    private class Pair {

        final int maximax,  depth;

        public Pair(int maximax, int depth) {
            this.maximax = maximax;
            this.depth = depth;
        }

        @Override
        public String toString() {
            return "Pair: maximax=" + maximax + " on depth " + depth;
        }
    }
    /**
     * AI
     * i want to memoize maximax, but return the memo'd part ONLY when i've computed
     * it already for a greater depth. (aka the depth param was lower)
     */
    private static HashMap<State, Pair> memo = new HashMap<State, Pair>();
    private long hits = 0,  miss = 0,  count = 0;// just for debug

    /**
     * maxmimax version with tons of debug info:
     */
      private int maxiMaxAlphaBeta(State s, int depth, final int max_depth, int alpha, int beta) {
        count++;// just for debug
        if (debug && depth < d) {
            System.out.println(init(depth) + ">maximax (a=" + alpha + ", b=" + beta + ") for " + s);
        }
        if (s.isTerminal() || depth == max_depth) {
            if (debug && depth < d) {
                System.out.println(init(depth) + " -> cutoff on depth "+depth+"!  reason="+(s.isTerminal()?"Terminal":"max depth")+" s.moves="+s.remainingMoves); //WTF!?!?!
            }
            //return s.score_ZeroSum();
            return s.score();
        }
        if (memo.containsKey(s) && memo.get(s).depth <= depth) {
            hits++;
            if (debug && depth < d) {
                System.out.println(init(depth) + "-> memo hit!  " + memo.get(s));
            }
            return memo.get(s).maximax;
        } else {
            miss++;
        }
        int bestScore = -1000;
        final State[] successors = s.expand();// AI <- sorted from best to worst score for first player

        Action ba = null; // just for debug
        for (State child : successors) {
            final int x = -maxiMaxAlphaBeta(child, depth + 1, max_depth, -beta, -alpha);
            if (debug && depth < d) {
                System.out.println(init(depth) + " the minimax best is x=" + x + " for child " + child);
            }
            if (x > bestScore) {
                ba = child.getLastAction();// just for debug
                if (debug && depth < d) {
                    System.out.println(init(depth) + x + " by doing " + child.getLastAction() + " is BETTER! than the previous best, " + bestScore + " by doing " + ba);
                }
                bestScore = x;
            } else if (debug && depth < d) {
                System.out.println(init(depth) + x + " by doing " + child.getLastAction() + " is not better than the previous best, " + bestScore + " by doing " + ba);
            }
            if (x > alpha) {
                alpha = x;
            }
            if (alpha >= beta) {
                if (debug && depth < d) {
                    System.out.println(init(depth) + "============ alpha-beta CUTOFF! alpha=" + alpha + "  beta=" + beta + "=============");
                }
                break;
            }
        }

        if (debug && depth < d) {
            System.out.println(init(depth) + "-> best score for first player is " + bestScore + " after doing " + ba + " in " + s + "\n");
        }
        memo.put(s, new Pair(bestScore, depth));
        return bestScore;
    }

    private String init(int depth) {
        String ans = " ";
        for (int i = 0; i < depth; i++) {
            ans += "    ";
        }
        return depth + ans;
    }
}
